define(['verifyInput','simpleTree'],function(){
    var currPageObj={};
    currPageObj.init=function(){
        var self = this;
        queryUserPageList(1);
    	
      //$(window).resize();
    	
        currPageObj.initEvents();
    };

    //绑定事件
    currPageObj.initEvents=function(){
        var self = this;
        $(".page-info").on("click","li",function(){
    		var topage = $(this).attr("page");
    		if(topage != "#"){
    			queryUserPageList(topage);
    		}
    	});
        
        $("#pageSize").on("change",function(){
        	queryUserPageList(1);
    	});
    	
    	$("#deleteSel").on("click",function(){
        	deleteSel();
    	});
        
        $("#checkAll").click(function(){
    		$(".table_style1 input[type='checkbox']").prop('checked', $("#checkAll").prop('checked'));
    	})
    	
    	$("#searchBtn").click(function() {
    		queryUserPageList(1);
    	});
    	
    	$(".operation .operation_add").click(function() {
    		showUserAdd();
    	});
    	
    	$(".add .cancel").click(function() {
    		disshowUserEdit();
    	});
    	
    	$(".add .submit").click(function() {
    		saveOrEditUser();
    	});
    	
    	$(".setrole .cancel").click(function() {
    		disshowUserMapRole();
    	});
    	
    	$(".setrole .submit").click(function() {
    		saveUserMapRole();
    	});
    };
    return currPageObj;
});

function freshData() {
	var topage = $(".page-info .cur-page").attr("page");
	if(topage != "#" && topage !="undefined"){
		queryUserPageList(topage);
	}
}

var curPage=0;
var totalPage=0;
function queryUserPageList(currentpage) {
	var pageSize = $("#pageSize").val();
	var userName = $("#searchUserName").val();
	var data = $.ajax({
		type : 'post',
		url : 'sysmgr/user/getUserPageList.htm',
		data : 'username=' + userName+'&currentpage=' + currentpage+'&pageSize='+pageSize,
		cache : false,
		success : function(data) {
			
			if(data.error){
				return;
			}
			$("#checkAll").attr("checked",false);
			var res =  data.data;
			userPagelist = res.dataList;
			curPage = res.currentPage;
			totalPage = res.totalPage;
			totalCount = res.totalCount;
			var listString = "";
			$("#pageDataList").empty();
			for(var i=0; i<userPagelist.length; i++){
				var listItem = userPagelist[i];
				var rank = parseInt((curPage-1)*pageSize+i*1+1);
				var userid = listItem.stUserId;
				var userName = listItem.stUserName;
				var stName = listItem.stName;
				var stTelPhone = listItem.stTelPhone;
				var nmOrder = listItem.nmOrder;
				if(i % 2 == 1){
					listString+="<tr class='even'>";
				}else{
					listString+=" <tr>";
				}
				listString+="    <td><input name=\"\" type=\"checkbox\" value=\""+userid+"\" /></td>";
				listString+="    <td >"+rank+"</td>";
				listString+="    <td><span title="+userName+">"+ userName+ "</span></td>";
				listString+="    <td><span title="+stName+">"+ stName+ "</span></td>";
				listString+="    <td><span title="+stTelPhone+">"+ stTelPhone+ "</span></td>";
				listString+="    <td><span title="+nmOrder+">"+ nmOrder+ "</span></td>";
				listString+="    <td ><span><a class=\"modify\" onclick=\"showUserEdit('"+userid+"')\" href='javascript:;'>编辑</a>&nbsp;&nbsp;<a class=\"modify\" onclick=\"showUserMapRole('"+userid+"','"+stName+"')\" href='javascript:;'>角色</a>&nbsp;&nbsp;<a class=\"modify\" onclick=\"deleteUser('"+userid+"')\" href='javascript:;'>删除</a></span></td>";
				listString+=" </tr>";
			}
			$("#pageDataList").append(listString);
			$("#totalCount").html(totalCount);
			setPageInfoPart(parseInt(curPage),parseInt(totalPage));
		},
		error : function() {
		}
	});
}

function mouseOver(tip)
{
	$("#"+tip).css("display","inline-block");
	}
	function mouseOut(tip)
	{
	$("#"+tip).css("display","none");
}
	//设置页码
	function setPageInfoPart(curPage, totalPage) {
		$(".page-info .page").remove();
		var startPage = curPage - 5;//要显示的起始页码
		var endPage = curPage + 5;
		
		if(startPage<=0){
			startPage = 1;
		}
		if(endPage >= totalPage){
			endPage = totalPage;
		}
		var showPageNum = endPage - startPage+1;//要显示的页码总数
		//添加页码元素
		var lastElem = $(".page-info .pre");
		var count = 0;
		if(startPage>1){
			$(
					"<li page=1 class='page'>1</li>").insertAfter(lastElem);
			lastElem = $(".page-info .page:eq(" + count + ")");
			count++;
		}
		if(curPage - 1>=10){
			$(
					"<li page='#' class=' page '>……</li>").insertAfter(lastElem);
			lastElem = $(".page-info .page:eq(" + count + ")");
			count++;
		}
		for ( var i = count; i < showPageNum+count; i++) {
			if (curPage == startPage) {
				$(
						"<li page=\""+startPage+"\" class=\"page cur-page\">"
								+ startPage + "</li>").insertAfter(lastElem);
			} else {
				$(
						"<li page=\""+startPage+"\" class=\"page\">"
								+ startPage + "</li>").insertAfter(lastElem);
			}
			lastElem = $(".page-info .page:eq(" + i + ")");
			startPage++;
		}
		count = i;
		
		if(totalPage - curPage >=10){
			$(
					"<li page='#' class=' page '>……</li>").insertAfter(lastElem);
			lastElem = $(".page-info .page:eq(" + count + ")");
			count++;
		}
		if(endPage<totalPage){
			$(
					"<li page="+totalPage+" class='page'>"+totalPage+"</li>").insertAfter(lastElem);
			lastElem = $(".page-info .page:eq(" + totalPage + ")");
			count++;
		}
		//设置首页，上一页，下一页，最后一页页码
		if(curPage == 1){
			$(".page-info .first").css("display","none");
			$(".page-info .pre").css("display","none");
		}else{
			$(".page-info .first").css("display","inline-block");
			$(".page-info .pre").css("display","inline-block");
			
			
			$(".page-info .first").attr("page", 1);
			$(".page-info .pre")
					.attr("page", (curPage - 1) > 0 ? (curPage - 1) : 1);
		}
		if(curPage == totalPage){
			
			$(".page-info .next").css("display","none");
			$(".page-info .last").css("display","none");
		}else{
			$(".page-info .next").css("display","inline-block");
			$(".page-info .last").css("display","inline-block");
			$(".page-info .next").attr("page",
					(curPage + 1) > totalPage ? totalPage : (curPage + 1));
			$(".page-info .last").attr("page", totalPage);
		}

	}

function showUserAdd() {
	$(".add .title").text("添加用户");
	$(".tan .tan_min").animate({opacity:1,"margin-top":"0"},600);
	$(".add").fadeIn();
}

function showUserEdit(id) {
	var data = $.ajax({
		type : 'post',
		url : 'sysmgr/user/getUserEdit.htm',
		data : 'userid='+id,
		cache : false,
		success : function(data) {
			var res = data.data;
			var userinfo = res.userinfo;
			//var rolelist = res.allroles;
			
			$("#stUserId").val(userinfo.stUserId);
			$("#stUserName").val(userinfo.stUserName);
			$("#stName").val(userinfo.stName);
			
			$("#stTelPhone").val(userinfo.stTelPhone);
			$("#nmOrder").val(userinfo.nmOrder);
			
//			var listString = "<option value=\"\"></option>";
//			$("#stPid").empty();
//			$("#stPid").append(listString);
			
			$(".add .title").text("修改用户");
			$(".tan .tan_min").animate({opacity:1,"margin-top":"0"},600);
			$(".add").fadeIn();
		},
		error : function() {
		}
	});
	
}

function disshowUserEdit() {
	$(".tan .tan_min").animate({opacity:1,"margin-top":"-500"},600);
	$(".add").fadeOut();
	$(".add .text").val("");
}

function saveOrEditUser(){
	if(checkInput()){
		var userId = $("#stUserId").val().trim();
		var userName = $("#stUserName").val().trim();
		var stUserPwd = $("#stUserPwd").val().trim();
		var stName = $("#stName").val().trim();
		var stTelPhone = $("#stTelPhone").val().trim();
		var nmOrder = $("#nmOrder").val().trim();
		var data = $.ajax({
			type : 'post',
			url : 'sysmgr/user/saveOrEditUser.htm',
			data : 'userId=' + userId+'&userName=' + userName+'&userPwd=' + stUserPwd+'&stName=' + stName+'&stTelPhone=' + stTelPhone+'&nmOrder=' + nmOrder,
			cache : false,
			success : function(data) {
				alert(data.msg);
				freshData();
				disshowUserEdit();
			},
			error : function() {
			}
		});
	}
	
}

function deleteUser(ids){
	if(confirm("确定要删除吗？")){
		var data = $.ajax({
			type : 'post',
			url : 'sysmgr/user/deleteUser.htm',
			data : 'userId=' + ids,
			cache : false,
			success : function(data) {
				alert(data.msg);
				freshData();
			},
			error : function() {
			}
		});
	}
	
}

function deleteSel(){
	var idList=[];
	 $(".table_style1").find('tr :checkbox:checked').each(function(){
		 var id = $(this).attr('value');
		 idList.push(id);
	 });   
	 if(idList.length>0){
		 var ids = idList.join(',');
		 //调用删除用户接口
		 deleteUser(ids);
	 }
	 else{
		 alert("至少选择一条数据删除！");
	 }
}

function showUserMapRole(id,name){
	
	var data = $.ajax({
		type : 'post',
		url : 'sysmgr/user/getUserMapRole.htm',
		data : 'userid='+id,
		cache : false,
		success : function(data) {
			var res = data.data;
			var usermaplist = res.userMap;
			var rolelist = res.roleList;
			
			$("#setUserId").val(id);
			$("#showUserName").html(name);
			
			var listString = "<ul>";
			for(var i=0; i<rolelist.length; i++){
				var selected = false;
				var listItem = rolelist[i];
				for(var k=0; k<usermaplist.length; k++){
					if(usermaplist[k].stRoleId == listItem.stRoleId){
						selected = true;
						break;
					}
				}
				if(selected){
					listString+="<li><input type=\"checkbox\" value=\""+listItem.stRoleId+"\" checked> <a href=\"javascript:;\" >"+listItem.stRoleName+"</a></li>";
				}
				else{
					listString+="<li><input type=\"checkbox\" value=\""+listItem.stRoleId+"\"> <a href=\"javascript:;\" >"+listItem.stRoleName+"</a></li>";
				}
				
			}
			listString +="</ul>";
			$(".setrole .st_tree").empty();
			$(".setrole .st_tree").append(listString);
			
			$(".tan .tan_min").animate({opacity:1,"margin-top":"0"},600);
			$(".setrole").fadeIn();
		},
		error : function() {
		}
	});
}

function disshowUserMapRole() {
	$(".tan .tan_min").animate({opacity:1,"margin-top":"-500"},600);
	$(".setrole").fadeOut();
	$(".setrole checkbox").val("");
}

function saveUserMapRole(){
	var userId = $("#setUserId").val();
	var checkArr = [];
    $(".setrole").find(':checkbox:checked').each(function(){
        var id = $(this).val();
        checkArr.push(id);
    });
    
	var data = $.ajax({
		type : 'post',
		url : 'sysmgr/user/saveUserMapRoles.htm',
		data : 'userId=' + userId+'&rolemaps=' + checkArr.join(','),
		cache : false,
		success : function(data) {
			alert(data.msg);
			disshowUserMapRole();
		},
		error : function() {
		}
	});
}

function checkInput(){
	var userId = $("#stUserId").val();
	var userName = $("#stUserName").val();
	if(userName.trim() == ""){
		alert("请输入用户名！");
		$("#stUserName").focus();
		return false;
	}
	if(userId.trim() == ""){
		var stUserPwd = $("#stUserPwd").val();
		if(stUserPwd.trim() == ""){
			alert("请输入密码！");
			$("#stUserPwd").focus();
			return false;
		}
		var stUserPwdConfirm = $("#stUserPwdConfirm").val();
		
		if(stUserPwdConfirm.trim() == ""){
			alert("请输入确认密码！");
			$("#stUserPwdConfirm").focus();
			return false;
		}
		
		if(stUserPwdConfirm != stUserPwd){
			alert("两次输入的密码不一致！");
			$("#stUserPwdConfirm").focus();
			return false;
		}
	}
	
	var stName = $("#stName").val();
	if(stName.trim() == ""){
		alert("请输入姓名！");
		$("#stName").focus();
		return false;
	}
	var stTelPhone = $("#stTelPhone").val();
	if(stTelPhone.trim() == ""){
		alert("请输入联系电话！");
		$("#stTelPhone").focus();
		return false;
	}
	var nmOrder = $("#nmOrder").val();
	if(nmOrder.trim() != ""){
		if(isNaN(nmOrder)){
			alert("请输入数字！");
			$("#nmOrder").focus();
			return false;
		}
	}
	return true;
}
